package com.cyzy.esservice;

import com.cyzy.dto.QuestionsDTO;
import com.cyzy.esbean.EsQuestions;
import com.cyzy.mapper.QuestionsMapper;
import com.cyzy.service.OptionsService;
import com.cyzy.vo.QuestionOptions;
import com.cyzy.vo.Questions;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.client.elc.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class EsQuestionService {

    @Autowired
    private QuestionsMapper questionsMapper;

    @Autowired
    private OptionsService optionsService;

    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;

    public void initIndex(){
        //先用mybatisplus读取question表的数据
        List<Questions> list = questionsMapper.selectList(null);

        for (Questions item : list) {
            List<QuestionOptions> options = optionsService.getOptionsByQuestionId(item.getId());
            item.setQuestionOptions(options);
        }


        //将该List<Questions>转化为List<EsQuestions>
        List<EsQuestions> esQuestionsList = new ArrayList<>();
        list.forEach(item->{
            EsQuestions esQuestions = new EsQuestions();
            BeanUtils.copyProperties(item, esQuestions);
            esQuestionsList.add(esQuestions);
        });

        //
        IndexOperations indexOps = elasticsearchTemplate.indexOps(EsQuestions.class);
        if(indexOps.exists()){
            indexOps.delete();
        }
        indexOps.createMapping(EsQuestions.class);
        elasticsearchTemplate.save(esQuestionsList);

    }

}
